package com.ReactNativeBlobUtil;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Build;
import android.util.Log;

import java.security.MessageDigest;

public class ApkIntegrityChecker {

    public static String getCertificateFingerprint(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            String packageName = context.getPackageName();
            PackageInfo packageInfo;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES);
                Signature[] signatures = packageInfo.signingInfo.getApkContentsSigners();
                return getSHA256Fingerprint(signatures[0].toByteArray());
            } else {
                packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
                Signature[] signatures = packageInfo.signatures;
                return getSHA256Fingerprint(signatures[0].toByteArray());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getSHA256Fingerprint(byte[] cert) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(cert);
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isApkIntegrityValid(Context context, String expectedFingerprint) {
        String actualFingerprint = getCertificateFingerprint(context);
        return expectedFingerprint.equals(actualFingerprint);
    }
}
